package com.lagou.factory;

import com.lagou.annotation.QjcAutowired;
import com.lagou.annotation.QjcService;
import com.lagou.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@QjcService("proxyFactory")
public class ProxyFactory {

    @QjcAutowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /*
    JDK动态代理要求委托对象必须实现接口；
    如果没有实现接口则AOP会选择用CGLib来生成代理对象
     */

    /**
     * JDK动态代理：生成代理对象
     *
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJDKProxyInstance(Object obj) {
        // 返回代理对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                /**
                 *
                 * @param proxy：当前代理对象的应用
                 * @param method：当前被调用的方法
                 * @param args：方法中传递的参数
                 * @return
                 * @throws Throwable
                 */
                (proxy, method, args) -> {
                    // 开启事务
                    transactionManager.beginTransaction();
                    Object invoke = null;
                    try {
                        // 调用原有业务逻辑
                        invoke = method.invoke(obj, args);
                        // 提交事务
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 回滚事务
                        transactionManager.rollBack();
                        throw e;
                    }

                    return invoke;
                });
    }

    /**
     * CGLib动态代理：生成代理对象
     *
     * @param obj：委托对象
     * @return 代理对象
     * @author qiaojiacheng
     * @date 2021/8/2 9:27 上午
     */
    public Object getCGLibProxyInstance(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object invoke = null;
                // 开启事务
                transactionManager.beginTransaction();
                try {
                    // 调用原有业务逻辑
                    invoke = method.invoke(obj, objects);
                    // 提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 回滚事务
                    transactionManager.rollBack();
                    throw e;
                }

                return invoke;
            }
        });
    }

}
